//app工具方法
var first = false; //返回键初值
var apptools = {
	/*
	 * 日期转时间戳
	 */
	convertStamp: function(dateString) {
		var str = dateString.replace(/-/g, '/');
		var date = new Date(str);
		var stamp = date.getTime();
		return stamp;
	},
	/*
	 * 插入元素
	 */
	insertAfter: function(newElement, targetElement) {
		var parent = targetElement.parentNode;
		if(parent.lastChild == targetElement) {
			parent.appendChild(newElement);
		}else{
			parent.insertBefore(newElement, targetElement.nextSibling);
		}
	},
	/*
	 * 输入中文字符串，返还首字符
	 */
	getStringFirstLetter: function(arr) {
		if(!String.prototype.localeCompare)
			return null;
		var letters = "*abcdefghjklmnopqrstwxyz".split('');
		var zh = "阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀".split('');
		var segs = [];
		var curr;
		letters.forEach(function(item, i) {
			curr = {
				letter: item,
				data: []
			};
			arr.forEach(function(item2) {
				if((!zh[i - 1] || zh[i - 1].localeCompare(item2) <= 0) && item2.localeCompare(zh[i]) == -1) {
					curr.data.push(item2);
				}
			});
			if(curr.data.length) {
				segs.push(curr);
				curr.data.sort(function(a, b) {
					return a.localeCompare(b);
				});
			}
		});
		return segs;
	},
	/*
	 * 选择框的值
	 */
	radioButtonListener: function(className) {
		var rdsObj = document.getElementsByClassName(className);
		var checkVal;
		for(i in rdsObj) {
			if(rdsObj[i].checked) {
				checkVal = rdsObj[i].value;
			}
		}
		return checkVal;
	},
	/*
	 * 弹出软键盘
	 */
	showKeyboard: function() {
		var nativeWebview, imm, InputMethodManager;
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var Context = plus.android.importClass("android.content.Context");
			InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
			imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
		} else {
			nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
		}
		if(mui.os.android) {
			imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
		} else {
			nativeWebview.plusCallMethod({
				"setKeyboardDisplayRequiresUserAction": false
			});
		}
		setTimeout(function() {
			var inputElem = document.querySelector('input');
			inputElem.focus();
			inputElem.parentNode.classList.add('mui-active'); //第一个是search，加上激活样式
		}, 200);
	},
	getZipImg: function(imgPath, callback) {
		//获得一个压缩图片
		plus.io.resolveLocalFileSystemURL(imgPath, function(entry) {
			entry.file(function(file) {
				if(file.size / 1024 > 200) {
					var dsts = IMGUPDIR + file.name;
					//判断目标图片是否已压缩，若已经压缩过则直接使用，否则压缩
					plus.io.resolveLocalFileSystemURL(dsts, function(entry) {
						entry.file(function(file) {
							file.url = 'file://' + file.fullPath;
							callback(file);
						});
					}, function(error) {
						//目标图片没有压缩过则压缩
						lessen = Math.sqrt((200 * 1024 * 8) / (file.size * 24)) * 100 + '%';
						dsts = IMGUPDIR + file.size + file.name;
						plus.zip.compressImage({
							src: imgPath,
							dst: dsts,
							quality: 50,
							format: 'jpg',
							width: lessen,
							height: lessen,
							overwrite: true
						}, function(zipImg) {
							zipImg.url = zipImg.target;
							callback(zipImg);
						}, function(err) {
							callback(null);
						})
					})
				} else {
					file.url = 'file://' + file.fullPath;
					callback(file);
				}
			});
		}, function(err) {
			callback(null);
		});
	},
	/*
	 * base转码
	 */
	getBase64: function(path, callback) {
		callback = callback || mui.noop;
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			entry.file(function(file) {
				var reader = new plus.io.FileReader();
				reader.onloadend = function(evrnt) {
					// Get base64 data
					fileBase = {
						data: evrnt.target.result,
						type: 'image'
					};
					callback(fileBase)
				};
				reader.readAsDataURL(file);
			})
		}, function(err) {
			console.log('文件路径错误')
		})
	},
	/*
	 * 判断是否登陆
	 */
	isLoginOrNot: function() {
		var userInfo = localStorage.getItem('userInfo');
		if(!userInfo) {
			mui.toast('您还未登录，请先登录后操作');
			return false;
		} else {
			return true;
		}
	},
	/*
	 * 跳转到登录页面
	 */
	gotoLogin: function() {
		webtool.openPreView('../../ucenter/view/ucenter-login', function(wb) {
			wb.show('pop-in', 300);
		})
	},
	quitLoginInformWebview: function(quitWeb) {
		var allActivity = plus.webview.all();
		for(var i in allActivity) {
			mui.fire(allActivity[i], 'userChange', {
				data: false
			});
		}
		apptools.clearUserInfo();
		quitWeb.close();
		mui.toast('已注销');
	},
	/*
	 * 登陆成功后的通知事件
	 */
	loginInformWebview: function(loginWeb) {
		var allActivity = plus.webview.all();
		for(var i in allActivity) {
			mui.fire(allActivity[i], 'userChange', {
				data: true
			});
		}
		setTimeout(function() {
			loginWeb.close();
		}, 300)
		mui.toast('登录成功');
	},
	/*
	 * 吐司，waiting
	 */
	showNativeWaiting: function(toastInfo) {
		if(toastInfo) {
			mui.toast(toastInfo);
		}
		var waiting = plus.nativeUI.showWaiting();
		return waiting;
	},
	/*
	 * 验证手机
	 */
	checkMobile: function(tel) {
		var mblRegx = /^1[3|4|5|7|8]\d{9}$/;
		if(!mblRegx.test(tel)) {
			mui.toast('请输入正确的手机号码');
			return false;
		}
		return true;
	},
	checkAllPhone: function(tel) {
		var mblRegx = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
		var mblRegx2 = /^((\d{3,4}\-)|)\d{7,8}(|([-\u8f6c]{1}\d{1,5}))$/;
		if(!mblRegx.test(tel) && !mblRegx2.test(tel)) {
			mui.toast('请输入正确的号码');
			return false;
		}
		return true;
	},
	//验证密码
	checkpass: function(pass) {
		var passReg =/^[a-zA-Z0-9]\w{5,15}$/;
		if(!passReg.test(pass)) {
			mui.toast('密码以数字或字母开头,数字，字母，下划线随机组成6-16位有效值');
			return false;
		}
		return true;
	},
	/**获取本地是否安装客户端
	 * 
	 * @param {String} id
	 */
	isInstalled: function(id) {
		if(id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if(mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch(e) {}
		} else {
			switch(id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	},
	/**
	 * 时间戳友好解析
	 * @param {Object} sTime
	 */
	friendlyDate: function(sTime) {
		if(!sTime) return '';
		var myDate = new Date(sTime * 1000);
		var Year = myDate.getFullYear();
		var Month = myDate.getMonth() + 1;
		var Day = myDate.getDate();
		if(Month < 10) {
			Month = "0" + Month;
		}
		if(Day < 10) {
			Day = "0" + Day;
		}
		return Year + "." + Month + "." + Day;
	},

	/**
	 * 时间戳解析 改
	 * @param {int} unixTime
	 * @param {Object} type
	 */
	fmtUnixTime: function(unixTime, type) {
		return apptools.friendlyDate(unixTime);
	},
	//给页面注册一个失去焦点事件，专用于解决ios系统下input控件不会自动失去焦点
	iosBlur: function() {
		window.addEventListener('touchstart', function(e) {
			if(e.target.tagName != "INPUT") {
				document.activeElement.blur();
			}
		})
	},
	/*
	 * 隐藏身份证和手机号码部分信息
	 * type: id是身份证 mobile是手机
	 */
	hideIdentityInfo: function(item, type) {
		var hidNum = 12;
		type == 'id' ? hidNum = 12 : hidNum = 6;
		var repString = item.replace(item.substr(3, hidNum), "******");
		return repString;
	},

	getUserInfo: function() {
		var userInfo = localStorage.getItem('userInfo');
		return userInfo;
	},
	/*
	 * 注销，清除用户信息
	 */
	clearUserInfo: function() {
		localStorage.setItem('userInfo', '');
	},
	/*
	 * 保存用户信息
	 */
	setUserInfo: function(data) {
		localStorage.setItem('userInfo', JSON.stringify(data));
	},
	/*
	 * 确认是否退出app
	 */
	confirmQuit: function() {
		var btnArray = ['否', '是'];
		mui.confirm('是否退出app', '友情提示', btnArray, function(e) {
			if(e.index == 1) {
				plus.runtime.quit();
			}
		})
	},
	/*
	 * 两个dom的显示&隐藏
	 * @param{obj,obj,boolean}
	 */
	changePage: function(showObj, hideObj, key) {
		if(key) {
			showObj.style.display = "";
			hideObj.style.display = "none";
		} else {
			showObj.style.display = "none";
			hideObj.style.display = "";
		}
	},
	/*
	 * 单个dom的显示&隐藏
	 * @param{obj,boolean}
	 */
	showHide: function(targetdom, key) {
		key == true ? targetdom.style.display = "block" : targetdom.style.display = "none";
	},
	/*
	 * 重写返回键
	 */
	backQuit: function() {
		mui.back = function() {
			//首次按键，提示'再按一次退出程序'
			if(!first) {
				first = new Date().getTime();
				mui.toast('再按一次退出应用');
				setTimeout(function() {
					first = false;
				}, 1000);

			} else {
				if(new Date().getTime() - first < 1000) {
					plus.runtime.quit();
				}
			}
		}
	},
	
	};

//页面辅助方法
var webtool = {
	/*
	 * 返回关闭页面，用于一些不常用的页面，避免预载页面过多消耗性能
	 */
	backQuit: function() {
		mui.back = function() {
			var wb = plus.webview.currentWebview();
			wb.close();
		}
	},
	//返回键重写  关闭当前webview
	newback: function(){
		var oldback=mui.back;
		mui.back = function() {
		      plus.webview.currentWebview().close();
		      oldback();
		} 
//			//手机的返回键
	   plus.key.addEventListener('backbutton', function() {
		        plus.webview.currentWebview().close();
		        oldback();
		 }, false);
		
	  },
	
	/*
	 * 对mui.openwindow的二次封装，压缩页面代码
	 */
	openSimView: function(webview, extData, anima, delayTime) {
		extData = extData || '';
		anima = anima || '';
		delayTime = delayTime || '300';
		mui.openWindow({
			url: webUrl + '.html',
			id: webId,
			extras: {
				data: extData
			},
			styles: {
				scrollIndicator: 'none'
			},
			show: {
				aniShow: anima,
				duration: drtTime
			},
			createNew: false,
			waiting: {
				autoShow: false
			}
		})
	},
	/*
	 * 打开页面方法重写，点击时才进行预载，回调对象用show方法显示
	 * @param{String}
	 */
	openPreView: function(webview, callback) {
		var webId = webview;
		if(~webId.indexOf('/')) {
			webId = webId.substr(webId.lastIndexOf('/') + 1);
		}
		var wb = plus.webview.getWebviewById(webId);
		if(!wb) {
			wb = mui.preload({
				url: webview + '.html',
				id: webId,
			})
			setTimeout(function() {
				callback(wb);
			}, 500)
		} else {
			callback(wb);
		}

	},

};

/*
 * 按钮计时器对象
 * */
var verifyCount = function(obj, time) {
	countObj = this;
	this.Obj = obj;
	this.initText = obj.innerHTML;
	this.time = time;
	this.setTime = function(time) {
		countObj.time = time;
	};
	this.dec_time = function() {
		if(countObj.time > 0) {
			countObj.Obj.disabled = true;
			countObj.Obj.innerHTML = "重新获取" + countObj.time-- + 'S';
			setTimeout(countObj.dec_time, 1000)
		} else {
			countObj.Obj.innerHTML = countObj.initText;
			countObj.Obj.disabled = false;
		}
	};
	this.dec_time();
	return countObj;
};

var takePhoto = function(title, domclass, callback) {
	photoObj = this;
	this.title = title;
	this.getImage = function(domId, type) {
		var cmr = plus.camera.getCamera();
		var data = {};
		cmr.captureImage(function(path) {
			plus.gallery.save(path, function() {
				plus.io.resolveLocalFileSystemURL(path, function(entry) {
					var s = entry.toLocalURL();
					var waiting = apptools.showNativeWaiting('扫描证件中...');
					document.getElementById(domId).src = s;
					data.path = path;
					data.id = domId;
					data.waiting = waiting;
					data.type = type;
					callback(data);
				}, function(e) {
					console.log("读取拍照文件错误：" + e.message);
				});
			}, function(e) {
				outSet('保存失败: ' + JSON.stringify(e));
			});
		}, function(e) {
			outSet('取消拍照');
		}, {
			filename: IMGDOWNDIR,
			index: 1
		});
	};
	this.galleryImg = function(domId, type) {
		var data = {};
		plus.gallery.pick(function(path) {
			var waiting = apptools.showNativeWaiting('扫描证件中...');
			document.getElementById(domId).src = path;
			data.path = path;
			data.id = domId;
			data.waiting = waiting;
			data.type = type;
			callback(data);
		}, function(e) {
			outSet('取消选择图片');
		}, {
			filter: 'image'
		});
	};
	this.init = function() {
		mui('body').on('tap', '.plus-photo-button', function() {
			var objId = this.id;
			var type = this.getAttribute('type');
			if(mui.os.plus) {
				var a = [{
					title: "拍照"
				}, {
					title: "从手机相册选择"
				}];
				plus.nativeUI.actionSheet({
					title: photoObj.title,
					cancel: "取消",
					buttons: a
				}, function(b) {
					switch(b.index) {
						case 0:
							break;
						case 1:
							photoObj.getImage(objId, type);
							break;
						case 2:
							photoObj.galleryImg(objId, type);
							break;
						default:
							break
					}
				})
			}
		})

	}
	this.init();
	return photoObj;
}